<?php
define('ACC', true);
require('./include/init.php');

session_start(); 
//print_r($_SESSION);
$userid = $_SESSION['user_id'];


$company = new companymodel();
$companyinfo = $company->getcompanyinfo($userid);
$companyid = $companyinfo['company_id'];
$company_y = $companyinfo['company_y'];
$company_q = $companyinfo['company_q'];

$sellinfo = $_POST;
$selltothemarketmsg = '';
$finishedgood = $company->getfinishedgood($companyid);
$finishedgoodupdate = array();

if(!empty($sellinfo)){

foreach($sellinfo as $k=>$v){
    if(($v!='')&&($v!='0'))
    {
    $elementname = $company->getelementname($k);
    $succeed = $company->actionselltothemarket($companyid, $k, $v);
    if($succeed === false){
    $selltothemarketmsg = $selltothemarketmsg . '卖出' . $v . '个' .$elementname . '产品失败，因为存货不足。<br/>';
    }else{
    $selltothemarketmsg = $selltothemarketmsg . '卖出' . $v . '个' .$elementname . '产品成功，获得收入' . $succeed . '元。<br/>';
    $finishedgoodupdate[$k] = $finishedgood[$elementname] - $v;
    }
    }
}

    $cashequivalent = $company->getcash_equivalent($companyid);
    $finishedgood =  $company->getfinishedgood($companyid);
    $totalcashequivalent = 0;
    $totalfinishedgood = 0;
    foreach($cashequivalent  as $k=>$v){
        $totalcashequivalent = $totalcashequivalent + $v;
    }

    foreach($finishedgood  as $k=>$v){
        $totalfinishedgood = $totalfinishedgood +$v;
    }
    // 返回信息$msg
    // 总现金 $totalcashequivalent
    // 成品总数 $totalfinishedgood

    // print_r($finishedgood);
    
    
    
    
    
    echo "
    { \"selltothemarketmsg\" : \"{$selltothemarketmsg}\" , 
      \"totalcashequivalent\" : \"{$totalcashequivalent}\",
      \"totalfinishedgood\" : \"{$totalfinishedgood}\"";
      
    foreach($finishedgoodupdate as $k=>$v){
        echo ',
"numof' . $k . '" : "' . $v . '"'; 
    }
      
    echo '
    }
    ';

}

?> 